package uk.co.hs.web.util;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.springframework.web.servlet.ModelAndView;


/**
 * WebUtils.
 */
public class WebUtils
{
  public final static String ASC = "asc";
  public final static String DESC = "desc";

  /**
   * Calculates paging values from args, puts the result into the model
   * which is then used in jsp by <tags:pageNumbers>
   * @param aOffset
   * @param aLimit
   * @param aTotal
   * @param aSortBy field name to sort by
   * @param aSortType field sort type
   * @param aMav
   * @return Updated aMav
   */
  public static ModelAndView setPagingData(
      Integer aOffset, Integer aLimit, Integer aTotal,
      String aSortBy, String aSortType, ModelAndView aMav)
  {
    Integer currentPage  = (aOffset / aLimit)+1;
    Integer lastPage     =  aTotal  / aLimit;
    lastPage = ((aTotal % aLimit) > 0) ? lastPage+1 : lastPage;


    List<Integer> pageList = new ArrayList<Integer>();
    pageList.add(currentPage-2);

    for(int i = 0; i<4; i++)
    {
      pageList.add(pageList.get(i)+1);
    }

    Iterator<Integer> itr = pageList.iterator();

    //remove negatives and pages above last page
    while(itr.hasNext()){
      Integer page = itr.next();
      if(page<1 || page > lastPage)
      {
        itr.remove();
      }
    }

    return
    aMav.addObject("page_current", currentPage)
        .addObject("page_last", lastPage)
        .addObject("page_list", pageList)
        .addObject("page_offset", aOffset)
        .addObject("page_showLast", !pageList.contains(lastPage))
        .addObject("page_showFirst", !pageList.contains(1))
        .addObject("page_sortBy", aSortBy)
        .addObject("page_sortType", aSortType)
        .addObject("page_limit", aLimit);

  }





  /**
   * Merges Date with time
   * @param aDate The original date
   * @param aTime Time in format HH:mm:ss
   * @return new merged date
   */
  public static DateTime mergeDateAndTime(DateTime aDate, String aTime)
  {
    if(aDate == null || aTime == null || aTime.isEmpty() )
    {
      return aDate;
    }
    else{
      DateTime time =  DateTimeFormat.forPattern("HH:mm:ss").parseDateTime(aTime);

      return aDate.plusHours(time.getHourOfDay())
                  .plusMinutes(time.getMinuteOfHour())
                  .plusSeconds(time.getSecondOfMinute());
    }
  }



}
